class Solution:
    def leastInterval(self, tasks, n) -> int:
        mapper={}
        freqset={}
        for i in tasks:
            mapper[i]=0
            try:
                freqset[i]+=1
            except KeyError:
                freqset[i]=1
        count=0
        step=0
        route=[]
        cands=sorted(freqset.keys(),key=lambda x:freqset[x])
        while count<len(tasks):
            for i in mapper.keys():
                if mapper[i]!=0:
                    mapper[i]-=1
                    if mapper[i]==0 and freqset[i]>0:
                        if len(cands)>0 and freqset[i]>freqset[cands[0]]:
                            cands.append(i)
                        else:
                            cands.insert(0,i)
            if len(cands)!=0:
                key=cands.pop()
                mapper[key]=n+1
                freqset[key]-=1
                if freqset[key]==0:
                    del freqset[key]
                    del mapper[key]
                count+=1
            step+=1
        return step

s=Solution()
print(s.leastInterval(["A","A","A","B","B","B"],2))

'''
5%
70%
太垃圾了！！！！

'''